# -*- coding: UTF-8 -*-

import datetime
import sys
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger

__all__ = ['PromAlarmGroup']

class PromAlarmGroup(Base, SessionMixin):
    '''
    prometheus告警规则组
    '''
    __tablename__ = "prom_alarm_group"
    name = Column(String(256), nullable=False, index=True, comment='规则组名称')
    # host主机 or k8s容器
    classes = Column(String(128), nullable=False, comment='规则组归类')
    comment = Column(String(256), nullable=True, comment='规则组说明')
    alarm_set_uuid = Column(Integer, ForeignKey('prom_alarm_set.uuid'), comment='告警集')

    alarm_rules = relationship("PromAlarmRule", backref="prom_alarm_group")



    __table_args__ = (
        Index('idx_prom_alarm_group_name', 'name', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic'
        }
    )

    def __repr__(self):
        return f"<prom_alarm_group='{self.name}>"


    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }
        result["alarm_rules"] = [
            alarm_rule.object_to_dict(db)
            for alarm_rule in self.alarm_rules
        ]

        result["prom_alarm_set"] = self.prom_alarm_set.name

        return result







